<?php

/**
 * @Date:               2025-03-03 21:43:12
 * @Last Modified by:   wuchenge
 * @Author:             wuchenge
 */
namespace App\Models;

use App\Libraries\Utils;
use App\Models\Model;

class User extends Model
{
    /**
     * @var array
     */
    protected $fillable = [
        'pid',
        'pid_route',
        'status',
        'invite_code',
        'email',
        'pwd',
    ];

    /**
     * @var array
     */
    protected $guarded = ['id', 'created_at', 'updated_at'];

    /**
     * @var string
     */
    protected $table = 'users';

    protected static function boot()
    {
        parent::boot();
        // 监听模型创建事件，在写入数据库之前触发
        static::creating(function ($model) {
            // 如果模型的 invite_code 字段为空
            if (!$model->invite_code) {
                // 调用 findAvailableInviteCode 生成邀请码
                $model->invite_code = static::findAvailableInviteCode();
                // 如果生成失败，则终止
                if (!$model->invite_code) {
                    return false;
                }
            }
        });
    }

    /**
     *
     * @return mixed
     */
    public function info()
    {
        return $this->hasOne(UserInfo::class, 'user_id', 'id');
    }

    /**
     * @return mixed
     */
    public function children()
    {
        return $this->hasMany(User::class, 'pid', 'id');
    }

    /**
     * @param $id
     */
    public static function getWithInfoById($id)
    {
        return User::with(['info', 'info.level'])->find($id);
    }

    /**
     * 通过id获取用户信息
     */
    public static function getUserInfoById($id, $status = self::STATUS_YES)
    {
        $query = self::where('id', $id);
        if ($status) {
            $query->where('status', $status);
        }

        return $query->first();
    }

    /**
     * @param $invite_code
     */
    public static function getUserByInviteCode($invite_code)
    {
        return self::where('invite_code', $invite_code)->first();
    }

    /**
     * @param $email
     * @param $password
     * @param $invite_code
     */
    public static function register($email, $password, $invite_code)
    {
        $parent    = self::getUserByInviteCode($invite_code);
        $pid       = 0;
        $pid_route = '0-';

        if ($parent) {
            $pid       = $parent->id;
            $pid_route = $parent->pid_route . $parent->id . '-';
        }

        // 开启一个数据库事务
        $user = \DB::transaction(function () use ($email, $pid, $pid_route,
            $password) {

            // 创建一个用户
            $user = new User([
                'email'     => $email,
                'pid'       => $pid,
                'pid_route' => $pid_route,
                'pwd'       => User::encodePassword($password),
            ]);

            $nick_name = Utils::getRandomString(8, 5);
            // 写入数据库
            $user->save();

            UserInfo::create([
                'nick_name' => $nick_name,
                'user_id'   => $user->id,
            ]);

            return $user;
        });

        return $user;
    }

    /**
     * @return mixed
     */
    public static function findAvailableInviteCode()
    {
        for ($i = 0; $i < 10; $i++) {
            // 随机生成 6 位的字母加数字
            $inviteCode = Utils::getRandomString(6, 5);
            // 判断是否已经存在
            if (!static::query()->where('invite_code', $inviteCode)->exists())
                                                                               {
                return $inviteCode;
            }
            usleep(100);
        }
        \Log::warning(sprintf('find order no failed'));

        return false;
    }

    /**
     * @param $email
     */
    public static function getUserByEmail($email)
    {
        return self::where('email', $email)->first();
    }

    /**
     * 保存个人信息
     * @param $info
     */
    public static function saveProfile($info)
    {
        $user_info = UserInfo::where('user_id', $info['id'])->first();
        if (empty($user_info)) {
            return false;
        }

        $update = [];
        if (!empty($info['avatar'])) {
            $update['avatar'] = Utils::setImage($info['avatar']);
        }

        if (!empty($info['nick_name'])) {
            $update['nick_name'] = $info['nick_name'];
        }

        if (!empty($info['telegram'])) {
            $update['telegram'] = $info['telegram'];
        }

        // 不改数据直接返回
        if (empty($update)) {
            return true;
        }

        $res = UserInfo::where('user_id', $info['id'])->update($update);
        if ($res) {
            return true;
        }

        return false;
    }
}
